<template>
    <nly-content-wrapper>
        <nly-content>
            <a-tabs style="margin-top: 40px; height: 100%;" @change="tabChange">
                <a-tab-pane key="1" tab="记事本">
                    <div class="note-warpper">

                        <a-row :span="24" :gutter="[16,16]">
                            <a-col :xs="12" :sm="8" :md="8" :lg="6" :xl="6">
                                <div class="note-add" @click="AddItem">
                                    <a-icon type="plus" />
                                </div>
                            </a-col>
                            <a-col v-for="item in data" :key="item" :xs="12" :sm="8" :md="8" :lg="6" :xl="6">
                                <div class="note-item" @dblclick="EdiItem(item)">
                                    <div class="note-title-box ">
                                        <span class="note-title">
                                            {{item.title?item.title:"无主题"}}
                                        </span>
                                        <span class="note-option">
                                            <a-icon @click.stop="deleteNote(item.id)" type="close" />
                                        </span>
                                    </div>
                                    <div class="note-content">
                                        <a-textarea style="border:none;resize: none;"  readonly v-if="item.content" :value="item.content" :auto-size="{ minRows: 5, maxRows: 2 }">

                                        </a-textarea>
                                        <span v-else>
                                            无内容
                                        </span>
                                    </div>
                                    <div class="note-time">
                                        {{item.createDate}}
                                        <a-tag color="blue" style="float:right;margin-top: 3px;">
                                            {{item.contentType}}
                                        </a-tag>
                                    </div>
                                </div>
                            </a-col>
                        </a-row>
                    </div>

                    <!-- <div style="margin-top: 20px">
                        <a-button type="primary" class="crm-btn" @click="deleteNote">删除</a-button>
                        <a-button type="primary" class="crm-btn" @click="AddItem">新增</a-button>
                    </div>
                    <a-table :columns="columns" :components="components" :data-source="data" :scroll="{ x: 500, y: 500}" style="height: calc(100vh - 16rem);" bordered :pagination="pagination" @change="onTableChange" :row-selection="{selectedRowKeys: selectedKeys, onChange: selection}">
                        <template slot="content" slot-scope="text">
                            <div style="width: 100px;height: 22px;" v-html="text"></div>
                        </template>
                    </a-table> -->
                </a-tab-pane>
            </a-tabs>
            <!-- modal 弹窗  -->
            <drag-modal v-model="eidtModelShow" centered on-ok="handleok" :title="editItem.id ? '编辑' : '新增'" width="600px" @cancel="()=>{eidtModelShow=false}">
                <div id="components-form-demo-advanced-search">
                    <a-form class="ant-advanced-search-form" :form="form" :label-col="{ span: 4 }" :wrapper-col="{ span: 18 }" @submit="handleSubmit">
                        <a-row :gutter="24">
                            <a-col :span="20">
                                <a-form-item label="主题">
                                    <a-input v-decorator="['title', { rules: [{ required: false }] }]" placeholder="请输入主题" />
                                </a-form-item>
                            </a-col>
                            <a-col :span="20">
                                <a-form-item label="分类">
                                    <a-select v-model="selectVal" @change="selectChange">
                                        <a-select-option v-for="(item, index) in selectData" :key="item.id + index" :value="item.type">
                                            <div class="clearfix" style="width:100%">
                                                <div style="float:left">{{ item.type }}</div>
                                                <div style="float:right" class="hover-red" @click.stop="handleRemove(item)">
                                                    <a-icon type="close" />
                                                </div>
                                            </div>
                                        </a-select-option>
                                    </a-select>
                                </a-form-item>

                            </a-col>
                            <a-col :span="4" style="margin-top:10px;font-size:12px;margin-left:-20px">
                                <a-icon type="edit" @click="addShowType" />
                                <!-- <a-button type="primary" size="small" @click="addShowType">添加分类</a-button> -->
                            </a-col>
                            <a-col :span="20">
                                <a-form-item label="内容">
                                    <!-- <div ref="editor" style="text-align:left" class="editer"></div> -->
                                    <a-textarea placeholder="请填写记事本内容" v-model="editorContent" :auto-size="{ minRows: 5, maxRows: 2 }">

                                    </a-textarea>
                                </a-form-item>
                            </a-col>
                        </a-row>
                    </a-form>
                </div>
                <template slot="footer">
                    <a-button type="primary" html-type="submit" @click="handleSubmit">保存</a-button>
                    <!-- <a-button :style="{ marginLeft: '8px' }" @click="handleReset">重置</a-button> -->
                    <a-button :style="{ marginLeft: '8px' }" @click="() => (eidtModelShow = false)">关闭</a-button>
                </template>
            </drag-modal>

            <a-modal :visible="typeVisible" title="添加分类" @cancel="()=>{typeVisible = false}" @ok="saveTypeHandler" width="600px">
                <a-row :span="24">
                    <a-col :span="12">
                        <a-input v-model="typeName" maxLength="8" placeholder="请填写分类名称(8个字符)"></a-input>
                    </a-col>
                </a-row>
            </a-modal>
        </nly-content>
    </nly-content-wrapper>
</template>

<script>
import { listToMap } from "@/utils/tool/map";
import { components } from "@/utils/antTableComponents";
import { createEditor } from "@/utils/wangEditer";
import { pageList, save, deleteNote, deleteType, getType, saveType } from "@/api/personal/userNote";

const basePostData = {
    current: 1,
    size: 20
};

export default {
    data () {
        const columns = [
            {
                title: "主题",
                dataIndex: "title",
                key: "x",
                width: 350,
                align: "left",
                customRender: (text, row) => {
                    return (
                        <span>
                            <i class={row.title || ""} style="margin-right:5px;"></i>
                            <a style="color: #000;" href="javascript:;" onClick={() => this.EdiItem(row)}>{text}</a>
                        </span>
                    );
                }
            },
            {
                title: "内容",
                dataIndex: "content",
                key: "content",
                width: 400,
                scopedSlots: { customRender: 'content' },
            },
            {
                title: "创建时间",
                dataIndex: "createDate",
                key: "createDate",
                width: 150
            }
        ];

        //表格 头部 可伸缩
        this.components = components(columns);
        return {
            tabKey: 1,
            postData: { ...basePostData },
            data: [],
            count: 0,
            columns,
            form: this.$form.createForm(this, { name: "advanced_search" }),
            pagination: { //分页信息
                defaultPageSize: 20,
                current: 1,
                pageSize: 20,
                total: 0,
                showTotal: total => {
                    return (
                        <div>
                            共 {total} 条数据，每页
                            <a-input-number
                                value={this.pagination.pageSize}
                                min={1}
                                max={500}
                                onPressEnter={e => this.changePageSize(e)}
                            />
                            条
                        </div>
                    );
                },
                showQuickJumper: true,
                showLessItems: true
            },
            reporForm: {},
            show: false, //是否显示
            editItem: {}, //新增/编辑对象
            eidtModelShow: false,
            selectedIds: [],  //table选中id
            selectedData: [], //table选中数据
            editorContent: '',  //富文本内容
            selectedKeys: [],
            editor: null,

            typeName: null,
            typeVisible: false,
            selectData: [],
            selectVal: null
        };
    },
    mounted () {
        this.PageList();
        this.getSelectData();
    },
    methods: {
        addShowType () {
            this.typeVisible = true;
        },
        handleRemove (data) {
            let _this = this;
            this.$confirm({
                title: '提示',
                content: '您确定要删除该记录吗？',
                onOk () {
                    deleteType({ id: data.id }).then(response => {
                        if (response.code === 200) {
                            _this.$message.success("删除成功");
                            _this.getSelectData();
                        }
                    })
                },
                onCancel () {

                },
            });
        },
        saveTypeHandler () {
            let request = {
                type: this.typeName
            }
            saveType(request).then(res => {
                if (res.code === 200) {
                    this.$message.success('保存分类成功');
                    this.typeName = null;
                    this.typeVisible = false;
                    this.getSelectData();
                }
            })
        },
        getSelectData () {
            getType().then(res => {
                if (res.code === 200) {
                    if (res.data.length > 0) {
                        this.selectData = res.data;
                        // this.selectVal = this.selectData[0].type;
                    }
                }
            })

        },
        selectChange (e) {
            this.selectVal = e;
        },
        //tab 切换
        tabChange (key) {
            console.log(key);
            this.tabKey = key;
            this.PageList();
        },
        //添加
        AddItem () {
            this.editItem = {};
            this.editorContent = null;
            this.selectVal = null;
            this.handleReset();
            // const { editor } = this;
            // if (!editor) {
            //     this.$nextTick(function () {
            //         let div = this.$refs["editor"];
            //         let editorOnChange = (html) => {
            //             console.log("保存富文本：", html);
            //             this.editorContent = html
            //         }
            //         let newEditor = createEditor(div, editorOnChange);
            //         console.log("f富文本editor", newEditor)
            //         this.editor = newEditor;
            //         this.editor.txt.html("");
            //     });
            // } else {
            //     this.editor.txt.html("");
            // }
            this.eidtModelShow = true;
        },
        //编辑
        EdiItem (row) {
            let data = null;
            console.log(row);
            if (!row) {
                // if (this.selectedData.length != 1) {
                //     this.$message.warn("请选择一条数据");
                //     return false;
                // } else {
                data = this.selectedData[0];
                // }
            } else {
                data = row;
                this.selectedIds = [];
                this.selectedData = [];
                this.selectedKeys = [];
                this.selectedData[0] = row;
                this.selectedIds[0] = row.id;
            }

            this.eidtModelShow = true;
            // const { editor } = this;
            // if (!editor) {
            //     this.$nextTick(function () {
            //         let div = this.$refs["editor"];
            //         let editorOnChange = (html) => {
            //             console.log("保存富文本：", html);
            //             this.editorContent = html
            //         }
            //         let newEditor = createEditor(div, editorOnChange);
            //         console.log("f富文本editor", newEditor)
            //         this.editor = newEditor;
            //         this.editor.txt.html(data.content);
            //     });
            // } else {
            //     //文本框赋值
            //     this.editor.txt.html(data.content);
            // }
            this.editorContent = data.content;
            this.selectVal = data.contentType;
            //form赋值
            this.form = this.$form.createForm(this, {
                mapPropsToFields: () => {
                    return {
                        title: this.$form.createFormField({
                            value: data.title
                        })
                    };
                }
            });
            this.editItem = { ...data };
        },
        //删除便签
        deleteNote (id) {
            // if (this.selectedIds.length < 1) {
            //     this.$message.error("请选择要删除的便签");
            //     return;
            // }
            let _this = this;
            this.$confirm({
                title: '提示',
                content: '您确定要删除该便签吗？',
                onOk () {
                    deleteNote([id]).then(response => {
                        if (response.code == 200) {
                            _this.$message.success("删除成功");
                            _this.PageList();
                        } else {
                            _this.$message.error(response.message);
                        }
                    });
                },
                onCancel () {
                },
            });
        },
        // 获取列表
        PageList (status) {
            const { postData } = this;
            postData.type = 2
            pageList(postData).then(response => {
                if (response.code === 200) {
                    const { data } = response;
                    const { records, total, current, size } = data;
                    this.data = records;
                    Object.assign(this.pagination, {
                        total
                    });
                }
            }).catch(error => { });
        },

        //获取
        showFunction () {
            this.show = !this.show;
        },
        //表单重置
        handleReset () {
            this.form.resetFields();
        },
        //保存便签
        handleSubmit (e) {
            e.preventDefault();

            this.form.validateFields((err, values) => {
                if (!err) {
                    const id = this.editItem.id;
                    this.editItem = { ...values };
                    this.editItem.id = id;
                    this.editItem.content = this.editorContent;
                    console.log("开始保存:", this.editItem);
                    this.editItem.contentType = this.selectVal;
                    this.editItem.createDate = null;
                    this.editItem.type = 2;
                    if (!this.editItem.title && !this.editItem.content) {
                        this.$message.warning('主题和内容必须填写一项');
                        return;
                    }
                    save(this.editItem)
                        .then(response => {
                            if (response.code === 200) {
                                this.$message.success("保存成功");
                                //刷新 列表
                                this.PageList();
                                this.selectedKeys = [];
                                this.eidtModelShow = false;
                            }
                        })
                }
            });
        },
        //便签table选择
        selection (keys, info) {
            this.selectedKeys = keys;
            const ids = new Array();
            info.forEach(function (val) {
                ids.push(val.id);
            });
            this.selectedIds = ids;
            this.selectedData = info;
        },
        //table分页触发
        onTableChange (pagination, filters, sorter) {
            Object.assign(this.postData, {
                current: pagination.current,
                size: pagination.pageSize
            });
            Object.assign(this.pagination, {
                current: pagination.current,
                pageSize: pagination.pageSize
            });
            this.PageList();
        },
        changePageSize (e) {
            const value = e.target.value;
            const { pagination } = this;

            console.log(e, value);
            Object.assign(this.postData, {
                size: value
            });
            Object.assign(this.pagination, {
                pageSize: Number.parseInt(value)
            });
            this.PageList();
        },
        reset () {
            this.postData = { ...basePostData };
        },
        onCellChange (key, dataIndex, value) {
            const dataSource = [...this.detailData];
            const target = dataSource.filter(item => key === item.key)[0];
            if (target) {
                target[dataIndex] = value;
                this.detailData = dataSource;
            }
        },

    },
    watch: {}
};
</script>
<style scoped>
    .editer >>> .w-e-menu {
        padding: 5px 9px;
    }

    .form-inline label {
        justify-content: left !important;
    }
    .form-inline > .col {
        margin-bottom: 1.5rem !important;
    }
    .icons-list >>> .anticon {
        margin-right: 8px;
        font-size: 16px;
    }
    .ant-advanced-search-form {
        padding: 24px;
        background: #fbfbfb;
    }

    .ant-advanced-search-form .ant-form-item {
        display: flex;
    }

    .ant-advanced-search-form .ant-form-item-control-wrapper {
        flex: 1;
    }

    #components-form-demo-advanced-search .ant-form {
        max-width: none;
    }
    #components-form-demo-advanced-search .search-result-list {
        margin-top: 16px;
        background-color: #fafafa;
        min-height: 200px;
        text-align: center;
        padding-top: 80px;
    }

    .ant-popover-inner {
        z-index: 2999;
    }
    .div-line {
        width: 100%;
        height: 2px;
        background: #1890ff;
    }
    .search-bn {
        width: 80px;
        height: 35px;
        margin-left: 15px;
        display: block;
        text-align: center;
        line-height: 35px;
        float: left;
        cursor: pointer;
    }
</style>
<style lang="less">
    .note-warpper {
        padding: 10px;
        .note-add {
            width: 100%;
            height: 210px;
            line-height: 210px;
            font-size: 60px;
            color: #888;
            box-shadow: 0px 0px 5px #ccc;
            text-align: center;
            text-align: center;
            cursor: pointer;
        }
        .note-item {
            box-shadow: 0px 0px 5px #ccc;
            height: 210px;
            border-radius: 4px;
            .note-title-box {
                height: 40px;
                line-height: 40px;
                padding-left: 10px;
                overflow: hidden;
                border-bottom: 1px solid #eee;
                display: flex;
                .note-title {
                    flex: 0 0 90%;
                    font-weight: bold;
                    font-size: 16px;
                    overflow: hidden;
                }
                .note-option {
                    flex: 0 0 10%;
                    overflow: hidden;
                    float: right;
                    text-align: right;
                    padding-right: 5px;
                    cursor: pointer;
                }
            }
            .note-content {
                height: 140px;
                padding: 10px;
                overflow-y: auto;
            }
            .note-time {
                height: 30px;
                line-height: 30px;
                padding-right: 5px;
                text-align: center;
                border-top: 1px solid #eee;
            }
        }
        .note-item:hover {
            box-shadow: 0px 0px 5px #1890ff;
        }
    }
</style>
